package cn.jee.controller;

import cn.jee.entity.Stu;
import cn.jee.repository.StuRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.IOException;

@Controller
public class FileController {

  @Autowired
  private StuRepository stuRepository;


  @RequestMapping("/photo_input")
  public String showUploadForm(@RequestParam Long teacherId,
                               @RequestParam Long studentId,
                               Model model) {
    model.addAttribute("teacherId", teacherId);
    model.addAttribute("studentId", studentId);
    return "upload";
  }

  @RequestMapping("/savePhoto")
  public String handleFileUpload(@RequestParam Long teacherId,
                                 @RequestParam Long studentId,
                                 @RequestParam("file") MultipartFile file,
                                 RedirectAttributes redirectAttributes) throws IOException {
    if(file.isEmpty()){
      redirectAttributes.addFlashAttribute("msg", "请选择文件上传");
      return "redirect:/photo_input?teacherId=" + teacherId + "&studentId=" + studentId;
    } else {
      String fileName = file.getOriginalFilename();
      File destFile = new File("d:/" + fileName);
      file.transferTo(destFile);

      Stu stu = stuRepository.findById(studentId).orElse(null);
      if (stu != null) {
        stu.setPhoto(fileName);
        stuRepository.save(stu);
      }
    }
    return "redirect:/assignment/page?teacherId=" + teacherId;
  }

}
